<?php

class IntesysAction extends CommonAction
{
    public $dao;
    public $listmap = 1;
    public $listorder = 'id DESC';
    public $pagesize = 20;
	public $rollpage=6;
    //判断是否为微信
    public function is_weixin()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }
	public function display($temp = ''){
		$map  = "site_id = ".__SITEID__." and groupname = '".strtolower(GROUP_NAME)."' and (modelname = '".strtolower(MODULE_NAME)."' or modelname = '*') and (actionname = '".strtolower(ACTION_NAME)."' or actionname = '*')";
		$Systempages = M('Systempages') -> where($map) -> find();
		if($Systempages){
			$ModulesDB = D('Modules');
			$this->initView(); 
			echo $this->view -> fetch(TMPL_PATH.'Home/TemplateDefault/Public-header.html');
			echo $ModulesDB->getListToString($Systempages['page_view_id'],$this->view,false,true);
			echo $this->view -> fetch(TMPL_PATH.'Home/TemplateDefault/Public-footer.html');
			
		}else{
			if(IS_AJAX){
				$list = $_GET['list'];
				//$list = $this->fetch();
				$empty = 1;
				$statu=$list?1:0;
				if($this->get('list')){
					$empty = 0;
				}
				$this->initView();

			    die(json_encode(array('empty' => $empty,'tbody'=>$this->fetch($temp),'dump'=>$_REQUEST,'statu'=>$statu, 'pages' => $this-> view -> get('pages'))));	 
			}else{
				parent::display($temp);
			}
		}
	}
	
	protected function createMenu() {
        $group = M('Menugroup')->where(array('status' => 1,'typeid'=>1))->order('sort')->select();
        $node = M('Node');
		if (session(C('ADMIN_AUTH_KEY'))) {
			$ret = array();
            foreach ($group as $k => $v) {
				$list_menu = $node->where(array(
                    'status' => 1,
                    'gid' => $v['id'],
                    'level' => 2
                ))->order('sort')->select();
				
				
				if (count($list_menu) > 0) {
					$group[$k]['menu'] = $list_menu;
					$ret[] = $group[$k];
				} else {
					unset($group[$k]);
				}
            }
            return $ret;
        }else{
		
			
			
			$m=D('Member');
			$a = $m -> where(array('id' => session(C('USER_AUTH_KEY')))) -> getField('accesslist');
			$menu = unserialize($a);//
			//$menu = RBACM::getAccessList($this->UserInfo);
	
			
			if($menu['INTESYS']==''){$this->error('您没有管理权限');}
			$n = array();
			foreach ($menu['INTESYS'] as $kk => $vv) {
				if(!in_array('INDEX',array_flip($vv))){continue;}
				$n[] = "'" . ucwords(strtolower($kk)) . "'";
			}
			foreach(explode(',', C('NOT_AUTH_MODULE')) as $vo){
				$na[]="'" . ucwords(strtolower($vo)) . "'";
			}
			$map = implode(',', $n);
			$map=$map.','.implode(',',$na);//将不需要验证的模块也一起显示出来
			
			$ret = array();
			foreach ($group as $k => $v) {
				$list_menu = $node->where("status=1 and gid={$v['id']} and level=2 and name in($map)")->order('sort')->select();
				
				if (count($list_menu) > 0) {
					$group[$k]['menu'] = $list_menu;
					$ret[] = $group[$k];
				} else { 	
					unset($group[$k]);
				}
			}
			return $ret;
		}
       
    }
    
    public function _initialize()
    {   
	//if(__SITEID__ == 13){dump($this->memberInfo);}
	//$this->	tiketnum = $this->memberInfo['integralconfig']);
	//dump($this->memberInfo['site_id']);
	    /**/
		
		$this->__self__ = md5(__SELF__);
		
		if(strtolower(ACTION_NAME) == 'index'){
			$loadIndexUrl = '';
			if(C('URL_MODEL') == 2){
				 $loadIndexUrl = str_replace('index.php/','',__SELF__);
			}else{
				 $loadIndexUrl = __SELF__;
			}
			$per = $_REQUEST;
			unset($per['_URL_']);
			unset($per['theme']);
			unset($per['p']);
			
			//session(MODULE_NAME, $per);
			C('URL_MODEL', 0);
			setcookie('loadIndexUrl', U('index', $per), time() + 3600, '/');
		}
		
		
        //使用父类的初始化 parent::_initialize();
        import("@.ORG.Integrals.Integral");
        $this->initCommon();
		
		
		//
		if ($this->memberInfo['site_id'] != __SITEID__) {
			
			if($this->memberInfo['id'] == $this->siteInfo['member_id']){

				//找到创始站点的会员
				$memberInfo = M('Member') -> where(array('site_id' => __SITEID__, 'username' => $this->memberInfo['username'])) -> find();
				session('memberInfo',$memberInfo);
				session(C('USER_AUTH_KEY'),$memberInfo['id']);
				if($memberInfo['isadministrator']==1){
					session ( C ( 'ADMIN_AUTH_KEY' ), true );
				}
			}else{
				//session('memberInfo',NULL);
                redirect(U(C('USER_AUTH_GATEWAY')));
			}
        }
		//if(__SITEID__ == 291){dump($this->memberInfo);}
		
		
	
	
	
	
		

        if ($this->is_weixin() && $this->siteInfo['is_wxLogin'] > 0) {
            //dump(session('memberInfo'));exit;

			$memberInfo = session('memberInfo');
            if (!session('memberInfo') || (session('memberInfo') && $memberInfo['site_id'] != __RELATEID__)) {
                if (session('memberInfo')) {
                    session('memberInfo',NULL);
                }
                //dump(session('memberInfo'));exit;
                Vendor('Weixin.Weixin');
                $d['token'] = getSysVal('token');
                $d['appid'] = getSysVal('appid'); 
                $d['appsecret'] = getSysVal('appsecret');
				
                $this->weixin = new WeixinChat($d);
                if ($this->siteInfo['is_wxLogin'] == 1) {
                    $snsapi_base = 1;
                } elseif ($this->siteInfo['is_wxLogin'] == 2) {
                    $snsapi_base = 0;
                }
                $this->weixin->redirectGetOauthCode('http://' . $_SERVER['HTTP_HOST'] . __APP__ . "/Intesys/Public/getcode.html", $snsapi_base, intval($this->aff_id) . '_and_' . base64_encode(__SELF__));
            }

        }
		
        //App 检测
        if(isset($_POST['deviceId'])&&isset($_POST['username'])){
            $map['loginapp']=$_POST['deviceId'];
            $map['username']=$_POST['username'];
            $memberModel = D('Member');
            if ($memberModel->checkLogin($map)) {
                session('memberInfo', $memberModel->userInfo);
                //RBAC 记录当前用户信息 ！important
                import ( '@.ORG.RBACM' );
                
                $authInfo = RBACM::authenticate ( $map );
                if (! $authInfo) {
                    $this->error ( '登录错误：账户不存在或账户已被禁用！' );
                }
                session ( C ( 'USER_AUTH_KEY' ), $authInfo ['id'] );
                session ( 'loginUserName', !empty($authInfo ['nickname'])?$authInfo ['nickname']:$authInfo['username'] );
				if($authInfo['isadministrator']==1){
					session ( C ( 'ADMIN_AUTH_KEY' ), true );
				}
				$this->memberInfo = session('memberInfo');
                RBACM::saveAccessList();
            }
        }
        //Rbac检测
        if (C('USER_AUTH_ON')) {
			if (!session(C('USER_AUTH_KEY'))) {
			
				//跳转到认证网关
				if(C('URL_MODEL') == 2){
					 $jumpUrl = str_replace('index.php/','',__SELF__);
				}else{
					 $jumpUrl = __SELF__;
				}
				session('jumpUrl',$jumpUrl);
				session('siteid', cookie('siteid'));
				
				$nologin['info'] = '登录超时，请重新登录！';
				$nologin['status'] = 408;
				if(IS_AJAX){
					exit(json_encode($nologin));
				}
				redirect(U(C('USER_AUTH_GATEWAY')));
			}
            import('@.ORG.RBACM');
            if (!RBACM::AccessDecision(GROUP_NAME) ) {
                //检查认证识别号
				//dump($_REQUEST);exit;
				if(!in_array(MODULE_NAME, explode(',', C('NOT_AUTH_MODULE')))&&!(MODULE_NAME=='Task_daily'&&in_array(ACTION_NAME, explode(',', C('NOT_AUTH_ACTION'))))){
					
					// 没有权限 抛出错误 
					if (C('RBAC_ERROR_PAGE')) {
						// 定义权限错误页面
						redirect(C('RBAC_ERROR_PAGE'));
					} else {
						if (C('GUEST_AUTH_ON')) {
							
							$this->assign('jumpUrl', U(C('USER_AUTH_GATEWAY')));
						}
						// 提示错误信息
						//如果用户没有权限 ， 要求他绑定一个有权限的用户 ， 否则拒绝他进入系统
						//session('memberInfo',NULL);
						$this->error(L('_VALID_ACCESS_').":".__SELF__);
					} 
				}
            }
        }
        
		    $m=D('Member');
            $a = $m -> where(array('id' => session(C('USER_AUTH_KEY')))) -> Field('accesslist, isadministrator') -> find();
			$accessList = $a['accesslist'];
            $this->accessList=unserialize($accessList);
			if($a['isadministrator'] == 1){
				$this->accessList = array();
			}
            //$this->accessList = RBACM::getAccessList(session(C('USER_AUTH_KEY')));
            
        //sitemapxml();
        //实现列表排序
        if ($this->_get('sortField')) {
            $this->listorder = $this->_get('sortField');
            $this->assign('sortField', $this->_get('sortField'));
        }
        if ($this->_get('sortType')) {
            if($this->_get('sortField') && $this->_get('sortField') != ''){
			     $this->listorder.= " " . $this->_get('sortType');
			}
            if ($this->_get('sortType') == '' || $this->_get('sortType') == 'ASC') {
                $this->assign('sortType', 'DESC');
            } else {
                $this->assign('sortType', 'ASC');
            }
        }else{
			if($this->_get('sortField') && $this->_get('sortField') != ''){
			     $this->listorder.= " " . $this->_get('sortType');
			}
            if ($this->_get('sortType') == '' || $this->_get('sortType') == 'ASC') {
                $this->assign('sortType', 'DESC');
            } else {
                $this->assign('sortType', 'ASC');
            }
		}
        //实现列表分页条数
        if ($this->_get('pagesize')) {
            $this->pagesize = intval($this->_get('pagesize'));
            $this->assign('pagesize', $this->pagesize);
        }else{
			$this->pagesize=20;
		}
        $this->UserInfo = session(C('USER_AUTH_KEY') );
          $this->left_menu = $this->createMenu();
          $Mode_list = array(
            'access',
			'formcategory',
            'node',
            'role',
            'user',
            'ticket',
            'menugroup',
            'role_user',
            'member',
            'member_group',
            'member_access',
            'member_role_user',
			'modules_layout',
			'pages_layout',
            'info',
            'integral_rule',
            'integral_ruletype',
            'integral_log',
            'integral_type',
			'schedule',
			'score',
			'site',
			'task',
			'event'
        );
        if (in_array(strtolower(MODULE_NAME) , $Mode_list)) {
            $this->dao = D(MODULE_NAME);
        }
        $myTotal=D('Integral_number')->where("member_id =".$this->memberInfo['id']." and typename = 'Binte' ")->getfield('number');
        $this->myTotal=$myTotal==''?0:$myTotal;
        $monthstart=strtotime(date('Y')."-".date('m')."-1");
        $monthmap['time']=array('between',array($monthstart,time()));
        $monthmap['member_id']=$this->memberInfo['id'];
        $monthjoin=' __INTEGRAL_TYPE__ it on it.id = r.type_id';
        $thisMonth=D('Integral_log')->getTotalnum($monthjoin,$monthmap);
        $this->thisMonth=$thisMonth==''?0:$thisMonth;
        if((D('Member')->where('id = '.$this->memberInfo['id'])->getfield('isadministrator',false))!='1'){
            $this->intTotal="<span style=\"padding:10px\">您的总积分 <span style='color:#f00;font-size:16px;'>".$this->myTotal."</span>  本月得分 <span style='color:#f00;font-size:16px;'>".$this->thisMonth."</span></span>";
        }else{
            $this->intTotal='';
        }
        //$this->myLastLogin=D('Member')->where('id ='.$this->memberInfo['id'])->getfield('login_time');
        //用户总积分
        if ($this->UserInfo){
            //$totalnum=D('Integral_log')->where(array('member_id'=>$this->UserInfo))->Field('sum(changenum)')->getField('sum(changenum)');
            $totalnum=D('Integral_number')->where(array('member_id'=>$this->UserInfo))->group('member_id')->Field('sum(number)')->getField('sum(number)');
            $this->assign('membertotalnum', $totalnum);
        }
        if ($this->_get('openid')) {
            $map['openid'] = $this->_get('openid');
            $memberModel = D('Member');
            $memberModel->checkLogin($map);
            session('memberInfo', $memberModel->userInfo);
        }
		
        if ($this->is_weixin() && !$this->memberInfo) {
            dump($this->memberInfo);exit;
            session('jumpurl','__SELF__');
            redirect(U('Public/login'));
        }

        if (!$this->memberInfo) {
			dump($this->memberInfo);exit;
            redirect(U('Public/login'));
        }


        $this->userInfo = M('Member')->where(array('id' => $this->memberInfo['id']))->find();
		
		
		$giveintegral = false;
		//是否有积分分配权限
		$integralconfig = unserialize($this->userInfo['integralconfig']);
		foreach($integralconfig as $k => $v){
			if($v[0] > 0 && $v[2] > 0){
				$giveintegral = true;
			}
		}
		
		$this->integralconfig = $integralconfig;
	    $this->giveintegral = $giveintegral;
		
		//初始化设置
		if($this->userInfo['setup'] == 0){
			$this->assign('setup', 0);
			
		}
		
		
		
        if (!$this->userInfo) {
            redirect(U('Public/logout'));
        }
		
		//加载任务类
		import("@.ORG.Task.Task");
		
		
        //认证信息
        $this->assign('userInfo', $this->userInfo);
        $this->assign('username', $this->memberInfo['username']);
        $this->assign('userid', $this->memberInfo['id']);
        //$this->assign('info',$this->userinfo);

        //正在进行中的任务的列表
        $then=time();
        $start=mktime(0,0,0,date('m',$then),date('d',$then),date('Y',$then));
        $end=mktime(23,59,59,date('m',$then),date('d',$then),date('Y',$then));
        $sample= 'site_id ='.__SITEID__.' and realtime between '.$start.' and '.$end.' and temptask = 0';
        $sample.=" and ( reviewer_id =".$this->memberInfo['id'].' or member_id = '.$this->memberInfo['id'].' or creator_id = '.$this->memberInfo['id'].')';
        $count = D('task')->alias('t')->where($sample)->count();
        $task=D('task')->alias('t')->where($sample)->field('t.*')->order('realtime desc')->limit(5)->select();
        $this->assign('nowlisttask',$task);
        $this->assign('nowlistcount',$count);
        //end nowlist
		
		
		
		//第一访问当前链接i
		$mqdb = M('Memberrequest');
		$map  = "site_id = ".__SITEID__." and GroupName = '".strtolower(GROUP_NAME)."' and (ModuleName = '".strtolower(MODULE_NAME)."') and (ActionName = '".strtolower(ACTION_NAME)."' and member_id = ".$this->memberInfo['id'].")";
		
		$request = $mqdb -> where($map) -> find();
		if(!$request){
			$this->requestfirst = 1;
			//写入访问记录
			$requestdata['GroupName'] = strtolower(GROUP_NAME);
			$requestdata['ModuleName'] = strtolower(MODULE_NAME);
			$requestdata['ActionName'] = strtolower(ACTION_NAME);
			$requestdata['member_id'] = $this->memberInfo['id'];
			$requestdata['site_id'] = __SITEID__;
			$requestdata['dateline'] = time();
			$requestdata['url'] = __SELF__;
			$requestdata['IP'] = get_client_ip();
			$mqdb -> add($requestdata);
		}else{
			//第二次访问记录在另一张表中，这里的数据可以计算用户行为
			$qdb = M('Request');
			$requestdata['GroupName'] = strtolower(GROUP_NAME);
			$requestdata['ModuleName'] = strtolower(MODULE_NAME);
			$requestdata['ActionName'] = strtolower(ACTION_NAME);
			$requestdata['member_id'] = $this->memberInfo['id'];
			$requestdata['site_id'] = __SITEID__;
			$requestdata['dateline'] = time();
			$requestdata['url'] = __SELF__;
			$requestdata['IP'] = get_client_ip();
			$qdb -> add($requestdata);
		}
		
    }


    public function head()
    {
        $this->display('Public:head');
    }
	
	
	
	//搜索表单
	public function search(){
		
		$this->display();
	}
	
    //上传头像
    public function uploadImg()
    {
        import('ORG.Net.UploadFile');
        $upload = new UploadFile();                        // 实例化上传类
        $upload->maxSize = 100 * 1024;                    //设置上传图片的大小
        $upload->allowExts = array('jpg', 'png', 'gif', 'pdf', 'doc', 'xls', 'docx', 'xlsx');    //设置上传图片的后缀
        $upload->uploadReplace = true;                    //同名则替换
        $upload->saveRule = 'uniqid';                    //设置上传头像命名规则(临时图片),修改了UploadFile上传类
        //完整的头像路径
        $path = './Public/Uploads/avatar/' . $this->memberInfo['id'] . '/';
        if (!is_dir($path)) {
            mkdir($path, 511, true);
        }
        $upload->savePath = $path;
        if (!$upload->upload()) {                        // 上传错误提示错误信息
            $this->ajaxReturn('', $upload->getErrorMsg(), 0, 'json');
        } else {                                            // 上传成功 获取上传文件信息
            $info = $upload->getUploadFileInfo();
            $temp_size = getimagesize($path . $info['0']['savename']);
            if ($temp_size[0] < 100 || $temp_size[1] < 100) {//判断宽和高是否符合头像要求
                $this->ajaxReturn(0, '图片宽或高不得小于100px！', 0, 'json');
            }
            $data['picName'] = $info['0']['savename'];
            $data['status'] = 1;
            $data['url'] = __ROOT__ . '/Public/Uploads/avatar/' . $this->memberInfo['id'] . '/' . $data['picName'];
            $data['info'] = $info;

            $this->ajaxReturn($data, 'json');
        }
    }
    //通用文件上传
    public function _upload($file = 'file') {
        import("ORG.Net.UploadFile");
        $upload = new UploadFile(); 
        //设置上传文件大小
        $upload->maxSize = 3*1024*1024;
        $upload->allowExts = explode(',', C('UPLOAD_EXTS'));
        $upload->savePath = "./Public/Uploads/".__SITEID__.'/'. MODULE_NAME . "" . __SITEID__ . "-";
        //自动命名
        $upload->saveRule = 'uniqid';
		
		if($this->_post('rewrite')){
			$upload->saveRule = pathinfo($this->_post('rewrite'),PATHINFO_FILENAME);
	    }
        //创建目录
        $upload->savePath = $upload->savePath . date('Ymd', time()) . "/";
        if (!file_exists("$upload->savePath")) {
            mk_dir($upload->savePath);
        }
        //设置需要生成缩略图，仅对图像文件有效
        $upload->thumb = 1;
        //设置需要生成缩略图的文件后缀
        //$upload->thumbSuffix = "_thumb";
        //设置缩略图最大宽度
        $upload->thumbMaxWidth = $this->thumbMaxWidth;
        //设置缩略图最大高度
        $upload->thumbMaxHeight = $this->thumbMaxHeight;
        $upload->uploadReplace = true;
        if (!$upload->upload()) {
            $error = $upload->getErrorMsg();
            exit($error);
            return false;
        } else {
            $uploadSuccess = true;
            $uploadList = $upload->getUploadFileInfo();
			//路径入库
			$imgdata['img_url'] = '/' . trim($uploadList[0]['savepath'], './Public') . '/' . $uploadList[0]['savename'];
			$imgdata['site_id'] = __SITEID__;
			$imgdata['size'] = $uploadList[0]['size'];
			$imgdata['user_id'] = $this->userInfo['id'];
			$imgdata['cate_id'] = $this->_get('cate_id')?$this->_get('cate_id'):0;
			M('Img')->data($imgdata)->add();
            return '/' . trim($uploadList[0]['savepath'], './Public') . '/' . $uploadList[0]['savename'];
        }
    }
    //单文件上传
    public function upload() {
        if (isset($_FILES['file'])) {
            $this->name = isset($_POST['name']) ? $_POST['name'] : 'img_url';
            $info = $this->_upload('file');
            //dump($info);exit();
            if ($this->name != 'img_url') {
                exit("<script>window.parent.uploaded" . $this->name . "('" . $info . "','" . $this->name . "'); location.href='" . U('upload', array(
                    'name' => $this->name
                )) . "';</script>");
            } else {
                exit($info);
            }
        } else {
            $this->name = $this->_get('name');
			if($this->name == ''){
				$this->assign('name', 'img_url');
			}
            $this->display('Public:upload');
        }
    }
    //裁剪并保存用户头像
    public function cropImg()
    {
        //图片裁剪数据
        $params = $this->_post();                        //裁剪参数
        if (!isset($params) && empty($params)) {
            return;
        }

        //头像目录地址
        $path = './Public/Uploads/avatar/' . $this->memberInfo['id'] . '/';
        //要保存的图片
        $real_path = $path . $params['picName'];
        //临时图片地址
        $pic_path = $path . $params['picName'];
        import('ORG.ThinkImage.ThinkImage');
        $Think_img = new ThinkImage(THINKIMAGE_GD);
        //裁剪原图
        $Think_img->open($pic_path)->crop($params['w'], $params['h'], $params['x'], $params['y'])->save($real_path);
        //生成缩略图
        $Think_img->open($real_path)->thumb(100, 100, 1)->save($path . $$params['picName'] . '_100.jpg');
        $Think_img->open($real_path)->thumb(60, 60, 1)->save($path . $$params['picName'] . '_60.jpg');
        $Think_img->open($real_path)->thumb(30, 30, 1)->save($path . $$params['picName'] . '_30.jpg');
        $memberDB = M('Member');
        $savedata['img_url'] = '/Public/Uploads/avatar/' . $this->memberInfo['id'] . '/' . $params['picName'];
        $map['id'] = $this->memberInfo['id'];
        $memberDB->where($map)->data($savedata)->save();
        $this->success('上传头像成功', U('Index/index'));
    }


    public function showimgBox()
    {
        $this->assign('id', $this->_get('id'));
        $this->display('Public:imagesBox');
    }

    public function upload_Img()
    {

        if ($this->_post('imgo')) {
            $imgo_url2 = $this->_post('imgo_url');
            $imgo_url = $_SERVER['DOCUMENT_ROOT'] . $imgo_url2;
            header('Content-type: image/jpeg');
            $source = imagecreatefromjpeg($imgo_url);
            if ($this->_post('imgo') == 'left') {
                $jd = 90;
            }
            if ($this->_post('imgo') == 'right') {
                $jd = -90;
            }

            $rotate = imagerotate($source, $jd, 0);
            ImageJpeg($rotate, $imgo_url);
            echo json_encode($imgo_url2);

            exit;
        }


        $png = $this->_post('png');
        $this->assign('id', $this->_get('id'));
        if (!isset($png)) {
            $this->display('Public:upload_Img');
            exit();
        } else {


            $path2 = '/Public/Uploads/card/' . $this->memberInfo['id'] . '/' . time() . '.jpg';
            $path = $_SERVER['DOCUMENT_ROOT'] . $path2;


            if (!is_dir(pathinfo($path, PATHINFO_DIRNAME) . '/')) {
                mkdir(pathinfo($path, PATHINFO_DIRNAME) . '/', 511, true);
            }

            $this->base64_to_png("" . str_replace('data:image/jpeg;base64,', '', $png), $path);
            $url['img_url'] = $path2;
            //$this->db->where(array('member_id'=>$this->userInfo['id']))->save($url);
            echo "<script>window.parent.uploaded('{$path2}','" . $this->_get('id') . "');</script>";
            $this->display('Public:upload_Img');
        }


    }

    function base64_to_png($inputfile, $outputfile)
    {
        $imageData = $inputfile;
        $file = fopen($outputfile, "w");
        fwrite($file, base64_decode($imageData));
        fclose($file);
    }

    //统计会员
    public function userCount()
    {
        set_time_limit(0);

 




        echo D('Member_member')->where(array('member_id' => $this->memberInfo['id'], 'site_id' => __RELATEID__, 'deep' => array('elt',3)))->count();
    }
    //改变排序
    public function dosort($m = '') {
				
        if ($this->_post('sort')) {
            $data = explode(',', $this->_post('sort'));
			$m = $m == ''?MODULE_NAME:$m;
            $this->dao = M($m);
			//exit('asdfadsf');
            foreach ($data as $k => $v) {
                $onearr = explode('_', $v);
                $id = intval($onearr[0]);
                $d[$this->_post('field') ] = intval($onearr[1]);
                $this->dao->create($d);
                $re = $this->dao->where(array(
                    'id' => $id
                ))->save();
            }
            exit('OK');
        }
    }
    //改变图文列表推荐排序
    public function doRecSort() {
        if ($this->_post('sort')) {
            $data = explode(',', $this->_post('sort'));
            foreach ($data as $k => $v) {
                $onearr = explode('_', $v);
                $id = intval($onearr[0]);
                $d['is_rec'] = intval($onearr[1]);
                $this->dao->create($d);
                $re = $this->dao->where(array(
                    'id' => $id
                ))->save();
            }
            exit('OK');
        }
    }
    //改变图文列表置顶排序
    public function doTopSort() {
        if ($this->_post('sort')) {
            $data = explode(',', $this->_post('sort'));
            foreach ($data as $k => $v) {
                $onearr = explode('_', $v);
                $id = intval($onearr[0]);
                $d['is_top'] = intval($onearr[1]);
                $this->dao->create($d);
                $re = $this->dao->where(array(
                    'id' => $id
                ))->save();
            }
            exit('OK');
        }
    }
    //改变图文列表热门排序
    public function doHotSort() {
        if ($this->_post('sort')) {
            $data = explode(',', $this->_post('sort'));
            foreach ($data as $k => $v) {
                $onearr = explode('_', $v);
                $id = intval($onearr[0]);
                $d['is_hot'] = intval($onearr[1]);
                $this->dao->create($d);
                $re = $this->dao->where(array(
                    'id' => $id
                ))->save();
            }
            exit('OK');
        }
    }
    //改变微信图文列表排序
    public function doweixin_sort() {
        if ($this->_post('sort')) {
            $data = explode(',', $this->_post('sort'));
            foreach ($data as $k => $v) {
                $onearr = explode('_', $v);
                $id = intval($onearr[0]);
                $d['weixin_sort'] = intval($onearr[1]);
                $this->dao->create($d);
                $re = $this->dao->where(array(
                    'id' => $id
                ))->save();
            }
            exit('OK');
        }
    }
    //写入数据
    public function insert($data = '', $jumpUrl = '') {
		if($jumpUrl == ''){
			$jumpUrl =  U('Intesys/' . MODULE_NAME . '/index');
		}
        
        if ($this->dao->create($data)) {
            $result = $this->dao->add();
            if (false !== $result) {
				if(strtolower(MODULE_NAME) != 'site'){
				  $this->insert_data = $this->dao->where(array('id' => $result))->find();
				  //$this->insert_relate();
				}
				die(json_encode(array('status'=>1,"info"=>"数据添加成功","tbody"=>$this->insert_data)));
				/*echo json_encode(array(
					"status"=>1,
					"info"=>"数据添加成功",
					"data"=>[["Airi","Satou","Accountant","Tokyo"]]
				),JSON_UNESCAPED_UNICODE);*/
				$this->success('保存成功！',$jumpUrl);
				//redirect($jumpUrl);
            } else {
				//echo '{"info":'+$this->dao->getError()+',"status":0}';
                $this->error($this->dao->getError());
            }
        } else {
			//echo '{"info":'+$this->dao->getError()+',"status":0}';
            $this->error($this->dao->getError());
        }
    }
    public function _list($rename = '', $join = '', $field) {
        $map = $this->listmap;
        $order = $this->listorder;
		$rollpage=$this->rollpage;
        $pagesize = $this->pagesize;
        //计算总页数
        if ($join != '' || $rename != '') { //链接查询
            $count = $this->dao->alias($rename)->join($join)->where($map)->count();
            import('ORG.Util.Page');
            //实例化分页类
            $p = new Page($count, $pagesize);
            $this->list = $this->dao->alias($rename)->join($join)->where($map)->order($order)->Field($field)->limit($p->firstRow . ',' . $p->listRows)->select();
            $this->pages = $p->show();
        } else {
            $count = $this->dao->where($map)->count();
            import('ORG.Util.Page');
            //实例化分页类
            $p = new Page($count, $pagesize);
			$p->rollPage = $rollpage;
			
            $this->list = $this->dao->where($map)->order($order)->limit($p->firstRow . ',' . $p->listRows)->select();

            $this->pages = $p->show();
        }
    }
    //删除记录
    public function delete() {
			//$jumpUrl =  U('Intesys/' . MODULE_NAME . '/index');
        if ($this->_get('id')) {
            $map['id'] = array('in', $this->_get('id')
            );
            $result = $this->dao->where($map)->delete();
            //dump();
            if (false !== $result) {
				//echo '{"info":"数据删除成功","status":1}';
				//die(json_encode(array('info'=>'','status'=>1)));
                $this->success('删除成功!', $jumpUrl);
            } else {
				//echo '{"info":"数据删除失败","status":0}';
                $this->error('操作失败！');
            }
        }
    }
	//显示修改页
    public function edit($temp = '') {
        if ($this->_get('id')) {
            $map['id'] = $this->_get('id');
            $this->info = $this->dao->where($map)->find();
            $this->display($temp);
        } else {
            $this->error('参数错误');
        }
    }
    //这是更新数据
    public function update($data = array() , $jumpUrl = '') {
        if($jumpUrl == ''){
			$jumpUrl =  U('Intesys/' . MODULE_NAME . '/index');
		}
        if ($this->_post('id')) {
            unset($_POST['site_id']);
            $map['id'] = array('eq',$this->_post('id'));
            if (!empty($data)) {
                if (!$this->dao->create($data)) {
                    $this->error($this->dao->getError());
                }
            } else {
				
                if (!$this->dao->create()) {
                    $this->error($this->dao->getError());
                }
            }
            //dump($data);exit();
            //dump(I('post.'));exit();
            $result = $this->dao->save();
            
            if (false !== $result) {
				
				die(json_encode(array('status'=>1,"info"=>"数据更新成功","tbody"=>$_POST)));
                $this->success('更新成功', $jumpUrl);
            } else {
				echo '{"info":'+$this->dao->getError()+',"status":0}';
                $this->error($this->dao->getError());
            }
        } else {
			echo '{"info":"参数错误","status":0}';
            $this->error('参数错误');
        }
    }

    //生成推广二维码 
    public function createAffQrcode()
    {
		//查找分成配置
		if ($this->userInfo['level'] == 0) {
            //sendWXMsg($this->userInfo['openid'], '当前等级不能生成推广二维码！');
            exit('当前等级不能生成推广二维码！');
        }
        //import('ORG.Net.Http');
        //把二维码拉回到本地
        Vendor('Weixin.Weixin');
        $d['token'] = getSysVal('token');
        $d['appid'] = getSysVal('appid');
        $d['appsecret'] = getSysVal('appsecret');
        $this->weixin = new WeixinChat($d);

        $affid = 'aff_' . $this->memberInfo['id'];

        //exit($affid);

        $tiket = $this->weixin->createQrcode($affid, 1);
        $qrocde = 'http://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $tiket['ticket'];//exit($qrocde);
        $qrcodelocal = './Public/qrcode/' . $this->memberInfo['id'] . '/';
        //echo "<img src='".$qrocde."' />";
        if (!is_dir($qrcodelocal)) {
            mkdir($qrcodelocal, 511, true);
        }
        //拉取头像到本地
        import("ORG.Util.Image");
        //读取生成配置
        $config = unserialize($this->siteInfo['qrcodesetting']);
        curlDownload($qrocde, $qrcodelocal . 'qrcode.jpg');
        curlDownload($this->memberInfo['img_url'], $qrcodelocal . 'head.jpg');


        //$this->GrabImage($qrocde,$qrcodelocal.'qrcode.jpg');

        //二维码大小
        $qrsize = explode(',', $config['qrsize']);
        Image::thumb($qrcodelocal . 'qrcode.jpg', $qrcodelocal . 'qrcode.jpg', '', $qrsize[0], $qrsize[1], true);
        //头像大小
        $headsize = explode(',', $config['headsize']);
        Image::thumb($qrcodelocal . 'head.jpg', $qrcodelocal . 'head.jpg', '', $headsize[0], $headsize[1], true);

        //头像位置
        $headposition = explode(',', $config['headposition']);
        Image::water('./Public' . $config['qrbackground'], $qrcodelocal . 'head.jpg', $qrcodelocal . 'myqr.jpg', 100, $headposition[0], $headposition[1], false);


        //二维码位置
        $qrposition = explode(',', $config['qrposition']);
        Image::water($qrcodelocal . 'myqr.jpg', $qrcodelocal . 'qrcode.jpg', $qrcodelocal . 'myqr.jpg', 100, $qrposition[0], $qrposition[1], false);

        //Image::buildString('吴俊源', array(0,0,0), $qrcodelocal.'nickname.png', 'png', 0, false);

        Vendor('water.water');
        $markimg = new water($qrcodelocal . 'myqr.jpg');
        //生成姓名

        $markimg->color = $config['nicknamecolor'];
        $markimg->fontSize = $config['nicknamesize'];
        $markimg->fontFile = './Public/MSYHBD.TTC';
        $nicknameposition = explode(',', $config['nicknameposition']);
        $markimg->setMarkPos($nicknameposition[0], $nicknameposition[1]);
        $markimg->appendTextMark($this->memberInfo['nickname']);
        $markimg->write($qrcodelocal . 'myqr.jpg');
        $this->weixin->sendCustomMessage($this->memberInfo['openid'], $qrcodelocal . 'myqr.jpg', 'image');
        //发送信息
        sendWXMsg($this->memberInfo['openid'], $config['sendMsg']);
    }
	
	 //异步更新单个字段内容
    public function ajaxUpdate() {
        if ($this->_post('data')) {
            $data = explode(',', $this->_post('data'));
            $id = $data[1];
            $field = $data[0];
            $returndata = array();
            $one = $this->dao->where(array(
                'id' => $id
            ))->find();
            if (!is_array($one)) {
                $returndata['status'] = 0;
            } else {
                if ($one[$field] == 0) {
                    $savedate[$field] = 1;
                } else {
                    $savedate[$field] = 0;
                }
                $re = $this->dao->where(array(
                    'id' => $id
                ))->save($savedate);
                if ($re !== false) {
                    $returndata['status'] = 1;
                } else {
                    $returndata['status'] = 0;
                }
            }
        } else {
            $returndata['status'] = 0;
        }
        $returndata['data'] = $savedate[$field];
        echo json_encode($returndata);
    }
	
	
	
	
   public function detection()
    {
		$Detection=D('Detection');
        
        // 设置一个标记，当这个标记不等于0就代表这个模块在这次循环以被检测，那就直接break就好
        $detearray[Admin] = 0;
        $detearray[Member] = 0;
        $detearray[Position] = 0;
        $detearray[Table] = 0;
        
        $data = json_decode(S('data'), true);
 
        // 时间是否超过5分钟，超过5分钟清空这个缓存，并调用缓存方法,时间戳除以60转换成分钟四舍五入
        if ($Detection->excTime(time(),$data['time']) < 5) {
            
        $Dedata=M('Detection');
            $ActionData = $Dedata->where("site_id=" . __SITEID__)
                ->order('ActionTime desc')
                ->limit(10)
                ->select();
			
            foreach ($ActionData as $key => $val) {
                
                if ($Detection->excTime(time(),$val['ActionTime']) < 5) {
                    
                    $Detection->overTime($val['ActionName'], $detearray);
                }
            }
        } else {
            S('data', NULL);
            //判断是否有权限，然后再显示提示信息
            $Detection->punctuality();
        }
        
        echo S('data');
    } 

 
}   